<?php
/*
 * July 28, 2011
 http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 @author     Richard Wagener <code@securebucket.com>

 https://code.google.com/p/variable-apparatus/
*/

class tools {
	
	private $text,$return,$config;

	public function __construct() {
		// load custom configuration file or load defaults
		// purpose is so you can safely update this file without losing any settings
		$this->config = array();
		if (file_exists($GLOBALS['cleaned']["DOCUMENT_ROOT"].'/.plug-ins/php-handy-tools/config.inc.php')) include 'config.inc.php';
		else {
			$this->config['send_email']['sender_name'] = 'Email Notice';
			$this->config['send_email']['sender_email'] = 'notices@example.com';
		}
	}

	public function send_email($to,$name,$subject,$message,$url = '') {
	
		if($to == '') return '';
	
		$recipient = $to; //recipient
		$mail_body = "Don't reply to this email.\nThis is a notification...\n\n".$message."\n\n".$url; //mail body 
		$subject = $subject; //subject
		$header = "From: ". $this->config['send_email']['sender_name'] . " <" . $this->config['send_email']['sender_email'] . ">\r\n"; //optional headerfields
		
		mail($recipient, $subject, $mail_body, $header); //mail command :) 
	}

	public function get_vaild_host($url)
	{
		$url = $this->clean_data($url,'url-uri',false);
		if(!stristr($url,'http://') && !stristr($url,'https://')) $url= 'http://'.$url;
		
		$domain = parse_url($url);
		if(!is_array($domain)) return false;
		$splitDomain = explode('.',$domain['host']);
		
		$tldApproved = array('gov','edu','com','net','cc','co','info','org','me','mobi','us','biz','ca','ws','tv');
		$tldApproved = array_flip($tldApproved);

		if (!array_key_exists($splitDomain[''.(count($splitDomain) - 1).''], $tldApproved)) {
			return false;
		}
		
		if(count($splitDomain) == 2) { $finalDomain = $splitDomain[0].'.'.$splitDomain[1]; }
		elseif(count($splitDomain) > 2) { $finalDomain = $splitDomain[''.(count($splitDomain) - 2).''].'.'.$splitDomain[''.(count($splitDomain) - 1).'']; }
		else { return false; }

		$ip = gethostbyname($finalDomain);
		// ...but if it fails, FALSE is returned instead of the unresolved host
		if ($ip == $finalDomain) return false;
		
		return $finalDomain;
		
	}

	public function encode_email($email) { 
		return md5( strtolower( trim( $email ) ) );
	}

	public function get_gravatar( $email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array() ) {
		$url = 'http://www.gravatar.com/avatar/';
		$url .= md5( strtolower( trim( $email ) ) );
		$url .= "?s=$s&d=$d&r=$r";
		$url = '<img src="' . $url . '"';
		if ( $img ) {
			foreach ( $atts as $key => $val )
				$url .= ' ' . $key . '="' . $val . '"';
		}
		$url .= ' />';
		return $url;
	}


	public function encrypt($string, $key) {
		$result = '';
		for($i=1; $i<=strlen($string); $i++)
		{
		$char = substr($string, $i-1, 1);
		$keychar = substr($key, ($i % strlen($key))-1, 1);
		$char = chr(ord($char)+ord($keychar));
		$result.=$char;
		}
		return $result;
	}
	
	public function decrypt($string, $key) {
		$result = '';
		for($i=1; $i<=strlen($string); $i++)
		{
			$char = substr($string, $i-1, 1);
			$keychar = substr($key, ($i % strlen($key))-1, 1);
			$char = chr(ord($char)-ord($keychar));
			$result.=$char;
		}
		return $result;
	}

	public function roundNum($num,$type = 'halfofdecimal')
	{
		if($type == 'halfofdecimal')
		{
			if($num == "5") {$return = 5;}
			elseif($num >= "4.5"){$return = 4.5;}
			elseif($num >= "4"){$return = 4;}
			elseif($num >= "3.5"){$return = 3.5;}
			elseif($num >= "3"){$return = 3;}
			elseif($num >= "2.5"){$return = 2.5;}
			elseif($num >= "2"){$return = 2;}
			elseif($num >= "1.5"){$return = 1.5;}
			elseif($num >= "1"){$return = 1;}
		}
		
		if(!isset($return)) $return = '';
		return $return;
		
	}
	public function randomize_date($startDate,$endDate) { //makeRandomDateInclusive('2009-04-01','2009-04-03');
		 $days = round((strtotime($endDate) - strtotime($startDate)) / (60 * 60 * 24));
			$n = rand(0,$days);
			return date("Y-m-d",strtotime("$startDate + $n days"));    	
	}
	
	public function randomize_array($array,$limit = 1,$singleReturn = true) {
		shuffle($array); 
		if(($singleReturn) && ($limit == 1)) { $temparray = array_slice($array, 0, $limit); return $temparray[0]; }
		else
		{
			return array_slice($array, 0, $limit);
		}
	}

	public function splitIntoArray($string,$seperator = '|',$order = 'normal', $putInto = 'value') {
		if($putInto == 'value') {
		$return = array_filter(explode($seperator,$string));
		}
		return $return;
	}
	
	public function RemoveExtraSpaces($text) {
		return preg_replace("/[[:blank:]]+/"," ",trim(str_replace(array("\n","\r\n","\r"),'',$text)));
	}
	
	public function AlphaNumericOnly($text, $spacesAllowed = false) {
		if($spacesAllowed) { return preg_replace("{[^a-zA-z0-9 ]}", '', $text); }
		elseif(!$spacesAllowed) {  return preg_replace("{[^a-zA-z0-9]}", '', $text); }
	}

	public function highlightTerms($query, $text) {
		$query=explode(' ',str_replace(array('','\\','/','+','*','?','[','^',']','$','(',')','{','}','=','!','<','>','|',':','#','-','_'),'',$query));
		for($i=0;$i<sizeOf($query);$i++) 
		$text=preg_replace("/($query[$i])(?![^<]*>)/i","<span class=\"highlight\"><strong>\${1}</strong></span>",$text);
		return $text;
	}
	
	public function getParagraphSnippet($phrase, $text, $radius = 120, $ending = "...") {
		
		$phrase = $this->RemoveExtraSpaces($phrase);
		$phraseLen = strlen($phrase); 
	 
	   if($radius < $phraseLen) $radius = $phraseLen; 

		$phrases = explode (' ',$phrase);

		foreach ($phrases as $phrase) { $pos = strpos(strtolower($text), strtolower($phrase));  if($pos > -1) break; }
		
		$startPos = 0; 
		if ($pos > $radius) $startPos = $pos - $radius; 

		$textLen = strlen($text); 

		$endPos = $pos + $phraseLen + $radius; 
		if ($endPos >= $textLen) $endPos = $textLen; 

		$excerpt = substr($text, $startPos, $endPos - $startPos); 
		if ($startPos != 0) $excerpt = substr_replace($excerpt, $ending, 0, $phraseLen); 

		if ($endPos != $textLen) $excerpt = substr_replace($excerpt, $ending, -$phraseLen); 

		return $excerpt; 
		
	}
	
	public function getTextUpTo($text, $delimeter = ' ||| ') { 
		return substr($text,0,strpos($text, $delimeter));		
	}


	public function visibleEmail($email) {
		$split = explode("@",$email);
		$partOne = substr(trim($split[0]),0,ceil(strlen(trim($split[0])) / 2)).str_repeat('.',ceil(strlen(trim($split[0])) / 2));
		if(isset($split['1'])) $parttwo = $split['1']; else $parttwo = '';
		return $partOne."@".$parttwo;		
	}
	
	public function gettag($tagName, $content, $type = 'single') {
		// type = array   	|  single return
		if($type == 'array') { 
			preg_match_all('/(<'.$tagName.'.*>)(.*)(<\/'.$tagName.'>)/imxsU',$content,$patterns); 
			return $patterns[2];
		} else {
			$h1count = preg_match_all('/(<'.$tagName.'.*>)(.*)(<\/'.$tagName.'>)/imxsU',$content,$patterns); 
			$res = array(); 
			array_push($res,$patterns[2]); 
			array_push($res,count($patterns[2]));
			return $res[0][0]; 			
		}
	}	 

	public function get_metaRefresh($content,$attribute = 'refresh') {

		if($attribute == 'refresh') { $heep = 'http-equiv'; $attCHECK = '.*URL=(.*?)'; }
		else { $heep = 'name'; $attCHECK = '(.*?)'; }
		$array = preg_match_all('!<meta.*'.$heep.'="'.$attribute.'".*content="'.$attCHECK.'"!i', $content, $matches) ? $matches[1] : ''; 
		$return['refresh'] = $array[0];
		
		$re="<meta\s+name=['\"]??description['\"]??\s+content=['\"]??(.+)['\"]??\s*\/?>";
		preg_match("/$re/siU", $content, $matches);
		$return['description'] = $matches[1];
		
		/* get page's keywords */
		$re="<meta\s+name=['\"]??keywords['\"]??\s+content=['\"]??(.+)['\"]??\s*\/?>";
		preg_match("/$re/siU", $content, $matches);
		$return['keywords'] = $matches[1];			
		
		/* parse links */
		$re="<a\s[^>]*href\s*=\s*(['\"]??)([^'\">]*?)\\1[^>]*>(.*)<\/a>";
		preg_match_all("/$re/siU", $content, $matches);
		$return['links'] = $matches[2];
		
		return $return;
	}	
			
	public function remove_HTML($s , $keep = '' , $expand = 'script|style|noframes|select|option'){
        /**///prep the string
        $s = ' ' . $s;
        $k = array();
        /**///initialize keep tag logic
        if(strlen($keep) > 0){
            $k = explode('|',$keep);
            for($i=0;$i<count($k);$i++){
                $s = str_replace('<' . $k[$i],'[{(' . $k[$i],$s);
                $s = str_replace('</' . $k[$i],'[{(/' . $k[$i],$s);
            }
        }
        
        //begin removal
        /**///remove comment blocks
        while(stripos($s,'<!--') > 0){
            $pos[1] = stripos($s,'<!--');
            $pos[2] = stripos($s,'-->', $pos[1]);
            $len[1] = $pos[2] - $pos[1] + 3;
            $x = substr($s,$pos[1],$len[1]);
            $s = str_replace($x,'',$s);
        }
        
        /**///remove tags with content between them
        if(strlen($expand) > 0){
            $e = explode('|',$expand);
            for($i=0;$i<count($e);$i++){
                while(stripos($s,'<' . $e[$i]) > 0){
                    $len[1] = strlen('<' . $e[$i]);
                    $pos[1] = stripos($s,'<' . $e[$i]);
                    $pos[2] = stripos($s,$e[$i] . '>', $pos[1] + $len[1]);
                    $len[2] = $pos[2] - $pos[1] + $len[1];
                    $x = substr($s,$pos[1],$len[2]);
                    $s = str_replace($x,'',$s);
                }
            }
        }
        
        /**///remove remaining tags
        while(stripos($s,'<') > 0){
            $pos[1] = stripos($s,'<');
            $pos[2] = stripos($s,'>', $pos[1]);
            $len[1] = $pos[2] - $pos[1] + 1;
            $x = substr($s,$pos[1],$len[1]);
            $s = str_replace($x,' ',$s);
        }
        
        /**///finalize keep tag
        for($i=0;$i<count($k);$i++){
            $s = str_replace('[{(' . $k[$i],'<' . $k[$i],$s);
            $s = str_replace('[{(/' . $k[$i],'</' . $k[$i],$s);
        }
        
        return $this->RemoveExtraSpaces($s);
    }

	
	public function clean_data($data,$type = 'char',$spaces = true) {
			$data = $this->RemoveExtraSpaces($data);
			if($data == '') { return ''; }
						
			if($type == 'int') { 
				$data = preg_replace("{[^0-9]}", '', $data);
			}
			elseif($type == 'ip') { 
				$data =  preg_replace("{[^0-9.]}", '',$data);
			}
			elseif($type == 'ipcsv') { 
				$data =  preg_replace("{[^0-9., ]}", '',$data);
			}
			elseif($type == 'paragraph') { 
				if($spaces == true) { 
					$data =  preg_replace("{[^a-zA-z0-9().:;=?!@& ]}", '',$data);
				}
				else
				{
					
					$data =  preg_replace("{[^a-zA-z0-9().:;=?!@&-]}", '',$data);
				}
				
			}
			elseif($type == 'char') { 
				$data = $this->AlphaNumericOnly($data,true);
			}
			elseif($type == 'url-host')
			{
				if(substr($data,0,4) == 'http') 
				{
					$data = parse_url($data, PHP_URL_HOST);
				}
				else
				{
					$data = parse_url('http://'.$data, PHP_URL_HOST);
				}
				$data = str_replace("www.","",$data);
				$data = 'http://'.$data;
			}
			elseif($type == 'url-uri')
			{
				$data = preg_replace("{[^a-zA-z0-9 :/.&?%=-]}", '', $data);
			}			
			
			if(!$spaces) { $data = str_replace(' ','',$data); }
			
			return $data;
	}
	
	public function i2c_realip()	// Returns the real IP address of the user
	{ 
		// http://in2.php.net/source.php?url=/include/ip-to-country.inc
		// No IP found (will be overwritten by for
		// if any IP is found behind a firewall)
		$ip = FALSE;
		
		// If HTTP_CLIENT_IP is set, then give it priority
		if (!empty($GLOBALS['cleaned']['_SERVER']["HTTP_CLIENT_IP"])) {
			$ip = $GLOBALS['cleaned']['_SERVER']["HTTP_CLIENT_IP"];
		}
		
		// User is behind a proxy and check that we discard RFC1918 IP addresses
		// if they are behind a proxy then only figure out which IP belongs to the
		// user.  Might not need any more hackin if there is a squid reverse proxy
		// infront of apache.
		if (!empty($GLOBALS['cleaned']['_SERVER']['HTTP_X_FORWARDED_FOR'])) {
	
			// Put the IP's into an array which we shall work with shortly.
			$ips = explode (", ", $GLOBALS['cleaned']['_SERVER']['HTTP_X_FORWARDED_FOR']);
			if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
	
			for ($i = 0; $i < count($ips); $i++) {
				// Skip RFC 1918 IP's 10.0.0.0/8, 172.16.0.0/12 and
				// 192.168.0.0/16
				if (!preg_match('/^(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\./', $ips[$i])) {
					if (version_compare(phpversion(), "5.0.0", ">=")) {
						if (ip2long($ips[$i]) != false) {
							$ip = $ips[$i];
							break;
						}
					} else {
						if (ip2long($ips[$i]) != -1) {
							$ip = $ips[$i];
							break;
						}
					}
				}
			}
		}
	
		// Return with the found IP or the remote address
		return ($ip ? $ip : $GLOBALS['cleaned']['_SERVER']['REMOTE_ADDR']);
	}
	
	public function parsename($name)
	{
		$parseB = explode(" ",$name);
		$titleT = '';
		foreach($parseB as $key => $value)
		{
		$value = preg_replace('/[^0-9A-Za-z]/','',$value);
			if($value != "")
			{
			$parse[] = $value;
			}
		}
		$count = count($parse) - 1;
		
		$title = array('Mr','Mrs','Ms','Dr','Mme','Mssr','Mister','Miss','Doctor','Sir','Lord','Lady','Madam','Mayor','President');
		$pedigree = array('Jr','Sr','III','IV','VIII','IX','XIII');
		
		for($i = 0; $i < count($parse); $i++)
		{
		if($parse[$i] != "")
		{
			if($i == 0)
			{
				foreach($title as $key => $value)
				{
					if($parse[$i] == $value)
					{
					$build['title'] = $parse[$i];
					$titleT = 't';
					}
				}
				if($titleT != 't')
				{
				$build['fname'] = $parse[$i];
				}
			}
			if(($i > 0) && ($count != $i))
			{
				$testI = $i + 1;
				if($titleT == 't')
				{
				$build['fname'] = $parse[$i];
				unset($titleT);
				}
				elseif($titleT != 'f')
				{
				$titleT = 'f';
				$build['mname'] = $parse[$i];		
				}
				else
				{
					foreach($pedigree as $key => $value)
					{
						if($parse[$testI] == $value)
						{
							$build['lname'] = $parse[$i];
							$notFound = 'T';
						}
					}
					if($notFound != 'T')
					{
					$build['mname'] .= " ".$parse[$i];		
					}
				}
				
		
			}
			if($count == $i)
			{
				foreach($pedigree as $key => $value)
				{
					if($parse[$i] == $value)
					{
						$build['pedigree'] = $parse[$i];
					}
				}
		
				if(!isset($build['pedigree']) || $build['pedigree'] == "")
				{
				$build['lname'] = $parse[$i];
				}
			}
		}
		} // end for
		if(!isset($build['compilefname'])) $build['compilefname'] = '';
		if(!isset($build['compilelname'])) $build['compilelname'] = '';
		if($build['lname'] == "")
		{
		$build['lname'] = $build['mname'];
		unset($build['mname']);
		}
		if(isset($build['title']) && $build['title'] != "")
		{	
		$build['compilefname'] = "$build[title] ";
		}
		if(isset($build['fname']) && $build['fname'] != "")
		{
		$build['compilefname'] .= "$build[fname] ";
		}
		if(isset($build['mname']) && $build['mname'] != "")
		{
		$build['compilefname'] .= "$build[mname] ";
		}
		if(isset($build['lname']) && $build['lname'] != "")
		{
		$build['compilelname'] = "$build[lname] ";
		}
		if(isset($build['pedigree']) && $build['pedigree'] != "")
		{
		$build['compilelname'] .= "$build[pedigree] ";
		}
		
			return $build;
		}
	
		
	}


?>